<?php
/************************
 *  Codenova.pl Project
 *  Created by: Kamil Mrzygłód
 *
 *  (c) 2013 by Codenova.pl
 *  All Right Reserved
 ***********************/

namespace Modules\GotchaAdmin\Controllers;

use Exception;
use Gotcha\App\Extensions\GotchaCulturesExtension;
use Gotcha\App\Extensions\GotchaErrorsExtension;
use Gotcha\App\Extensions\GotchaLogsExtension;
use Gotcha\App\Extensions\HttpExtension;
use Gotcha\App\Framework\Controller;
use Gotcha\App\Types\String;
use GotchaDatabase\GotchaSettingsQuery;

class SettingsController extends Controller {
    public function Index() {
        return parent::View();
    }

    public function Edit() {
        return parent::View();
    }

    public function EditPost() {
        $http = new HttpExtension();

        // Validate input
        if(empty($_POST['Id']) || !isset($_POST['Id'])) {
            die('Error');
        }

        if(empty($_POST['StrongName']) || empty($_POST['Value']) || !isset($_POST['StrongName']) || !isset($_POST['Value'])) {
            header('Location: '.$http->resolveAbsoluteUrl().parent::UrlContent('/Admin/Settings/Edit?error=1&id='.$_POST['Id']));
            exit;
        }

        // Update setting
        try {
            $settings = GotchaSettingsQuery::create()
                ->findOneById($_POST['Id'])
                ->setStrongName($_POST['StrongName'])
                ->setValue($_POST['Value'])
                ->save();
        } catch(Exception $e) {
            GotchaLogsExtension::createNewLogEntry(new String($e->getMessage()));
            GotchaErrorsExtension::throwError(new String(GotchaCulturesExtension::getTranslation(new String('ERROR_DURING_EXECUTING_QUERY'))));
            exit;
        }

        header('Location: '.$http->resolveAbsoluteUrl().parent::UrlContent('/Admin/Settings'));
        exit;
    }

    public function returnSettings() {
        $settings = GotchaSettingsQuery::create()
                        ->orderById()
                            ->find();

        // String builder
        $html = '';
        foreach($settings as $setting) {
            $html .= '<tr>';
            $html .= sprintf('<td>%s</td><td>%s</td><td>[ <a href="%s?id=%s">Edytuj</a> ]</td>', $setting->getStrongName(), $setting->getValue(), parent::UrlContent('/Admin/Settings/Edit'), $setting->getId());
            $html .= '</tr>';
        }

        return $html;
    }

    public function returnSetting($id) {
        $settings = GotchaSettingsQuery::create()
                        ->findOneById($id);

        return $settings;
    }
}